package com.qf.gh.dao.impl;

import com.qf.gh.dao.OrderDao;
import com.qf.gh.domain.Order;
import com.qf.gh.utils.DateSourceUtils;
import com.qf.gh.utils.TxUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class OrderDaoImpl implements OrderDao {
    @Override
    public long findCountByAid(int parseInt) {
        String sql = "select count(0) from tb_order where aid=?";
        QueryRunner qr = new QueryRunner(DateSourceUtils.getDataSource());
        try {
            long count = (long) qr.query(sql, new ScalarHandler(), parseInt);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("查询该地址应用订单数量失败");
        }
        return 0;
    }

    @Override
    public void addOrder(Order order) {
        Connection conn = TxUtils.getConn();
        String sql="INSERT INTO `tb_order` (`id`, `uid`, `money`, `status`, `time`, `aid`) VALUES (?, ?, ?, ?, ?, ?)";
        QueryRunner qr=new QueryRunner();
        try {
            qr.update(conn,sql,order.getId(),order.getUid(), order.getMoney(), order.getStatus(), order.getTime(),order.getAid());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("新增订单失败");
        }
    }

    @Override
    public List<Order> select() {
        String sql = "select `id`, `uid`, `money`, `status`, `time`, `aid` from tb_order ";
        QueryRunner qr = new QueryRunner(DateSourceUtils.getDataSource());
        try {
            List<Order> orderList= qr.query(sql, new BeanListHandler<>(Order.class));
            return orderList;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("查询订单数量失败");
        }
        return null;
    }

    @Override
    public void update(String parseInt) {
        String sql = "update  tb_order set status=3 where id=? ";
        QueryRunner qr = new QueryRunner(DateSourceUtils.getDataSource());
        try {
            qr.update(sql,parseInt);

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("修改订单状态失败");
        }

    }

    @Override
    public List<Order> findByName(String toString, List<Object> parmas) {
        String sql = "select `id`, `uid`, `money`, `status`, `time`, `aid` from tb_order "+toString;
        QueryRunner qr = new QueryRunner(DateSourceUtils.getDataSource());
        try {
            List<Order> orderList= qr.query(sql, new BeanListHandler<>(Order.class),parmas.toArray());
            return orderList;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("模糊查询订单数量失败");
        }
        return null;
    }
}
